#!/usr/bin/perl -w

use strict;
use warnings;
use Data::Dumper;

use Mojolicious::Lite;
use Mojolicious::Plugin::Authentication;
use Mojolicious::Plugin::Bcrypt;
use Mojolicious::Plugin::Database;
use DBI;

my $database     = 'data/data.db';
my $echonest_api = 'GOWTS6J5HAXNQX8QR';

my $page        = "page1";
my $greeting    = "hi";

print "\n\nstarted again\n\n";

# database initialization
plugin 'database' => {
    dsn      => "dbi:SQLite:dbname=$database",
    username => q{},
    password => q{},
    options  => { RaiseError => 1 },
    helper   => 'db',

};

# Use strong encryption
plugin 'bcrypt';

# Authentication
plugin 'authentication' => {

    load_user => sub {

        my ( $self, $uid ) = @_;

        my $sth = $self->db->prepare(' select * from users where user_id=? ');

        $sth->execute($uid);

        if ( my $res = $sth->fetchrow_hashref ) {

            return $res;

        }
        else {

            return;
        }

    },

    validate_user => sub {

        my ( $self, $username, $password ) = @_;
        
        print "validating";
        my $sth
            = $self->db->prepare(' select * from users where user_name = ? ');

        $sth->execute($username);

        return unless $sth;

        if ( my $res = $sth->fetchrow_hashref ) {
            print Dumper $res;
            #my $salt = substr $password, 0, 2;

            #if ( $self->bcrypt_validate( $password, $res->{user_passwd} ) ) {
            if ( $res->{user_passwd} =~ /$password/ ) {
                print "kassa";

                $self->session(user => $username);

                #
                # For data that should only be visible on the next request, like
                # a confirmation message after a 302 redirect, you can use the
                # flash.
                #
                
                $self->flash(message => 'Thanks for logging in.');

                return $res->{user_id};

            }
            else {
                print "meup";

                return;

            }

        }
        else {

            return;

        }
    },

};

my $ua = Mojo::UserAgent->new;

# /login
######################

post '/' => sub {
   my $self = shift;
   
    my $user = $self->param('user') || q{};
    my $pass = $self->param('password') || q{};
    
    if ( $self->authenticate( $user, $pass ) ) {
        $self->redirect_to('/');
        #$self->render(template => 'authenticated', format => 'html', handler => 'ep');
    
    }
    else {
    
        $self->flash( message => 'Invalid credentials!' );
    
        $self->redirect_to('/');
    
    }
};

# /register
######################

any 'register' => sub {
   my $self = shift;
   my $user     = $self->param('user');
   my $pass     = $self->param('password1');
   
   print "ended in register\n";
   
   print "user: $user\n";
   print "pass: $pass\n";
   
   $self->render(template => 'authenticated', format => 'html', handler => 'ep');
};


# /
######################

get '/' => sub {
   my $self = shift;
   
   print "ended in /\n";
   
   if ( $self->session('user') ) {

        $self->render(template => 'authenticated', format => 'html', handler => 'ep');

    }
    else {

        $self->render(template => 'index', format => 'html', handler => 'ep');

    }

  
    
};

# /search
######################

any '/search' => sub {
  my $self  = shift;
  my $q     = $self->param('term');
  
  my $tx = $ua->get('http://developer.echonest.com/api/v4/song/search?api_key='.$echonest_api.'&title='.$q);
  my $result;
  my @songs;
  if (my $res = $tx->success) {
    $result = $res->json('/response/songs');
  }
  else {
    my ($err, $code) = $tx->error;
    say $code ? "$code response: $err" : "Connection error: $err";
  }
  
  print Dumper \$result;
  
  foreach my $i (@{$result}){
    push (@songs, $i->{title}." - ".$i->{artist_name});
  }
  
  $self->render(json => \@songs);
};



# static js.js
######################

get 'js.js' => sub {
  my $self = shift;
  
  $self->stash(page => $page);
  
  $self->render(template => 'js', format => 'js', handler => 'ep');
};

# static css
######################

get 'style.css' => sub {
  my $self = shift;
  
  $self->render(template => 'style', format => 'css', handler => 'ep');
};


app->start;